//
//  LBNiuAchiveVC.m
//  V-Learn
//
//  Created by Apple on 2019/1/2.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "LBNiuAchiveVC.h"
#import "FZXLipinduihuanCollectionViewCell.h"
#import "LBSectionHeaderView.h"
#import "JSDropDownMenu.h"
#import "LBNiuStudentDetailVC.h"
#import "LBDakaDetailVC.h"
#import "WKNiuwaModel.h"
static NSString *ID=@"FZXLipinduihuanCollectionViewCell";
@interface LBNiuAchiveVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,JSDropDownMenuDataSource,JSDropDownMenuDelegate>
@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *productArray;
@property (nonatomic, strong) NSString *preUrl;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageNums;
@property (nonatomic, assign) NSInteger condition;
@property (nonatomic, strong)     NSMutableArray *data3;
@property (nonatomic, strong) NSMutableArray *sourceData;
@property (nonatomic, strong) NSString *termNum;//选择后的学期号
@property (nonatomic, strong) NSString *ageNum;//选择后的年龄
@end

@implementation LBNiuAchiveVC{
    
    NSMutableArray *_data1;
    NSMutableArray *_data2;

    
    NSInteger _currentData1Index;
    NSInteger _currentData2Index;
    NSInteger _currentData3Index;
    
    NSInteger _currentData1SelectedIndex;
    NSInteger _currentSelectIndex;
    JSDropDownMenu *menu;
    
}
- (NSMutableArray *)sourceData{
    if (!_sourceData) {
        _sourceData = [NSMutableArray array];
    }
    return _sourceData;
}
- (NSMutableArray *)data3{
    if (!_data3) {
        _data3 = [NSMutableArray array];
    }
    return _data3;
}
- (NSMutableArray *)productArray{
    if (!_productArray) {
        _productArray = [NSMutableArray array];
    }
    return _productArray;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置滚动方向
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
//        layout.itemSize = CGSizeMake(166*kScaleFit, 228*kScaleFit);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT+40, SCREEN_WIDTH, SCREEN_HEIGHT-LBNAVBAR_HEIGHT-40) collectionViewLayout:layout];
        _collectionView.backgroundColor = rgb(242,242,242);
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.collectionView registerClass:[FZXLipinduihuanCollectionViewCell class] forCellWithReuseIdentifier:@"FZXLipinduihuanCollectionViewCell"];

    
    [self setupUI];
    //牛娃学期号
    [self requestniuwaQihao];
}
#pragma mark - 获取牛娃档案学期号接口
- (void)requestniuwaQihao{
    //牛娃档案学期号
    [WYHXNetWorkManager get:WKQueryAllTermNum_WKURL params:@{} completionHandler:^(id responseObj, NSError *error) {
//        NSLog(@"%@",responseObj);
        NSArray *dataArray = responseObj[@"data"];
        for (NSDictionary *dic in dataArray) {
            NSString *termNum = dic[@"termNum"];
            [self.data3 addObject:termNum];
        }
        [self.collectionView reloadData];
    }];
}


- (void)setupUI{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"牛娃档案";

    _data1 = [NSMutableArray array];
    _data2 = [NSMutableArray arrayWithObjects:@"3岁", @"4岁", @"5岁", @"6岁", @"7岁", @"8岁", nil];
    
    JSDropDownMenu *menu = [[JSDropDownMenu alloc] initWithOrigin:CGPointMake(0, LBNAVBAR_HEIGHT) andHeight:40];
    menu.indicatorColor = [UIColor colorWithRed:175.0f/255.0f green:175.0f/255.0f blue:175.0f/255.0f alpha:1.0];
    menu.separatorColor = [UIColor whiteColor];//[UIColor colorWithRed:210.0f/255.0f green:210.0f/255.0f blue:210.0f/255.0f alpha:1.0];
    menu.textColor = [UIColor colorWithRed:83.f/255.0f green:83.f/255.0f blue:83.f/255.0f alpha:1.0f];
    menu.dataSource = self;
    menu.delegate = self;
    
    _currentData1Index = 1;
    _currentData1SelectedIndex = 1;
    _currentSelectIndex = 0;
    [self.view addSubview:menu];
    
    //添加 collectionView
    [self.view addSubview:self.collectionView];
    
    //礼品兑换接口
    [self requestProductListData];
    
    [self.collectionView registerClass:[LBSectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Cell"];
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    [self setupRefresh];
}
- (void)clickMenuTitle:(NSString *)title{
    self.ageNum = nil;
    self.termNum = nil;
    [self setupRefresh];
}
//刷新
- (void)setupRefresh
{   //下拉
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupLoadData)];
    //上拉
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];
    
    [self.collectionView.mj_header beginRefreshing];
}
- (void)setupLoadData{
    _page = 1;
    _pageNums = 10;
//    [self setupData];
    if (_currentSelectIndex==1) {
        [self reqestNianlingData:self.ageNum];
    }else if (_currentSelectIndex==2){
        [self reqestQihaoData:self.termNum];
    }else{
       [self setupData:self.ageNum termnum:self.termNum];
    }
    
    //如果当前是在期号  需要调用期号接口
    
}
/**
 加载更多数据
 */
- (void)setupLoadMoreData{
    
    ++(_page);
    _pageNums = 10;

    [self setupData:self.ageNum termnum:self.termNum];
}//决定footer的状态
- (void)checkFooterState{
    
    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
}

- (void)menu:(JSDropDownMenu *)menu didSelectRowAtIndexPath:(JSIndexPath *)indexPath {
    
    if (indexPath.column == 0) {
        
        if(indexPath.leftOrRight==0){
            _currentData1Index = indexPath.row;
            return;
        }
        
    } else if(indexPath.column == 1){
        
        _currentData2Index = indexPath.row;
        self.ageNum = _data2[indexPath.row];
//        [self setupData:self.ageNum termnum:self.termNum];
        [self reqestNianlingData:self.ageNum];
//        NSLog(@"%@",self.ageNum);
    } else{
        
        _currentData3Index = indexPath.row;
        self.termNum = self.data3[indexPath.row];
        NSLog(@"%@",self.termNum);
//        [self setupData:self.ageNum termnum:self.termNum];
        [self reqestQihaoData:self.termNum];
    }
    _currentSelectIndex = indexPath.column;
    NSLog(@"menu==%@indexPath.row===%ld",menu,indexPath.column);
    
    
}

- (void)setupData:(NSString *)ageNum termnum:(NSString *)termNum{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];

    VKWeakSelf(self)

    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    [data setObject:token forKey:@"canNullToken"];
    [data setObject:@(_page) forKey:@"page"];
    [data setObject:@(_pageNums) forKey:@"num"];

    //userController/queryExcellentUserByAge 根据年龄查询接口
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKQueryExcellentUser_WKURL withPostParams:data withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.sourceData removeAllObjects];
            }

            for (NSDictionary *dic in result[@"data"]) {
                WKNiuwaModel *model = [WKNiuwaModel mj_objectWithKeyValues:dic];
                [self.sourceData addObject:model];
            }
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.collectionView.mj_footer endRefreshing];
            }
        }else{
//            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.collectionView reloadData];
        
        [self.collectionView.mj_header endRefreshing];
    }];
}
- (void)reqestNianlingData:(NSString *)ageNum{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    
    VKWeakSelf(self)
    NSString *age = [ageNum stringByReplacingOccurrencesOfString:@"岁" withString:@""];
//    NSLog(@"%@",age);
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    [data setObject:token forKey:@"canNullToken"];
    [data setObject:age forKey:@"age"];
    [data setObject:@(_page) forKey:@"page"];
    [data setObject:@(_pageNums) forKey:@"num"];

    //userController/queryExcellentUserByAge 根据年龄查询接口
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKQueryExcellentUserByAg_WKURL withPostParams:data withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.sourceData removeAllObjects];
            }
            
            for (NSDictionary *dic in result[@"data"]) {
                WKNiuwaModel *model = [WKNiuwaModel mj_objectWithKeyValues:dic];
                [self.sourceData addObject:model];
            }
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.collectionView.mj_footer endRefreshing];
            }
        }else{
            //            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.collectionView reloadData];
        
        [self.collectionView.mj_header endRefreshing];
    }];
}
- (void)reqestQihaoData:(NSString *)termNum{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    
    VKWeakSelf(self)

    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    [data setObject:token forKey:@"canNullToken"];
    [data setObject:termNum forKey:@"termNum"];
    [data setObject:@(_page) forKey:@"page"];
    [data setObject:@(_pageNums) forKey:@"num"];
    
    //userController/queryExcellentUserByAge 根据年龄查询接口
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKQueryClocksByTermNum_WKURL withPostParams:data withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.sourceData removeAllObjects];
            }
            
            for (NSDictionary *dic in result[@"data"]) {
                WKNiuwaModel *model = [WKNiuwaModel mj_objectWithKeyValues:dic];
                [self.sourceData addObject:model];
            }
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.collectionView.mj_footer endRefreshing];
            }
        }else{
            //            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.collectionView reloadData];
        
        [self.collectionView.mj_header endRefreshing];
    }];
}
//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    return CGSizeMake(166*kScaleFit, 228*kScaleFit);
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size = CGSizeMake(SCREEN_WIDTH, 10);
    return size;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    WKNiuwaModel *model = self.sourceData[indexPath.row];
    //在这里进行点击cell后的操作
    LBNiuStudentDetailVC *niuDetailVC = [LBNiuStudentDetailVC new];
    niuDetailVC.attenUserId = model.userId;
    niuDetailVC.babyUsername = model.babyUsername;
    niuDetailVC.babyNickname = model.babyNickname;
    niuDetailVC.studyNum = model.studyNum;
    niuDetailVC.babyInfo = model.babyInfo;
    niuDetailVC.ageYear = model.ageYear;
    niuDetailVC.isVip = model.isVip;
    niuDetailVC.sex = model.sex;
    NSString *url = [NSString stringWithFormat:@"%@%@",Public_URL,model.headImg];
    niuDetailVC.headImg = url;
    [self.navigationController pushViewController:niuDetailVC animated:YES];
}

- (void)requestProductListData{

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.sourceData.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *ID=@"FZXLipinduihuanCollectionViewCell";
    FZXLipinduihuanCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    WKNiuwaModel *model = self.sourceData[indexPath.row];
    cell.followButton.tag = indexPath.row+33344;
    [cell.followButton addTarget:self action:@selector(clickfollowBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.model = model;
    return cell;
}
#pragma mark - 关注按钮
- (void)clickfollowBtn:(UIButton *)sender{
    NSInteger index = sender.tag-33344;
    WKNiuwaModel *model = self.sourceData[index];
    NSString *token = [UserModel getUserModel].token;
    if ([model.isAtten isEqualToString:@"1"]) {
        [WYHXNetWorkManager post:WKCancelFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {

            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                model.isAtten = @"0";
                [self.sourceData replaceObjectAtIndex:index withObject:model];

                [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:index inSection:0], nil]];
            }
        }];
    }else{
        [WYHXNetWorkManager post:WKFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {
//            NSLog(@"%@",responseObj);
            NSString *code = responseObj[@"code"];
            NSString *msg = responseObj[@"msg"];
            if ([code integerValue]==200) {
                model.isAtten = @"1";

                [self.sourceData replaceObjectAtIndex:index withObject:model];
                [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:index inSection:0], nil]];
            }else if ([code integerValue]==203)
            {
                [MBProgressHUD showSuccess:msg toView:self.view];
                return ;
            }
        }];
    }

    
}
//- (CGSize )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    return CGSizeMake(SCREEN_WIDTH/2-11, 198);
//}
//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //    return UIEdgeInsetsMake(0, 2, 0, 2);
    return UIEdgeInsetsMake(0, 15, 0, 15);
}
- (CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 8;
}
- (CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 8;
}

- (NSInteger)numberOfColumnsInMenu:(JSDropDownMenu *)menu {
    
    return 3;
}

-(BOOL)displayByCollectionViewInColumn:(NSInteger)column{
    
    if (column==2) {
        
        return NO;
    }
    
    return NO;
}

-(BOOL)haveRightTableViewInColumn:(NSInteger)column{
    
    if (column==0) {
        return NO;
    }
    return NO;
}

-(CGFloat)widthRatioOfLeftColumn:(NSInteger)column{
    
    if (column==0) {
//        return 0.3;
        return 1;
    }
    
    return 1;
}

-(NSInteger)currentLeftSelectedRow:(NSInteger)column{
    
    if (column==0) {
        
        return _currentData1Index;
        
    }
    if (column==1) {
        
        return _currentData2Index;
    }
    
    return 0;
}

- (NSInteger)menu:(JSDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column leftOrRight:(NSInteger)leftOrRight leftRow:(NSInteger)leftRow{
    
    if (column==0) {
        if (leftOrRight==0) {
            
            return 0;//_data1.count;
        } else{
            
//            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
//            return [[menuDic objectForKey:@"data"] count];
            return _data1.count;
        }
    } else if (column==1){
        
        return _data2.count;
        
    } else if (column==2){
        
        return _data3.count;
    }
    
    return 0;
}

- (NSString *)menu:(JSDropDownMenu *)menu titleForColumn:(NSInteger)column{
    
    switch (column) {
        case 0: return @"全部";//_data1[0];//[[_data1[0] objectForKey:@"data"] objectAtIndex:0];
            break;
        case 1: return @"年龄";//_data2[0];
            break;
        case 2: return @"学期";//_data3[0];
            break;
        default:
            return nil;
            break;
    }
}

- (NSString *)menu:(JSDropDownMenu *)menu titleForRowAtIndexPath:(JSIndexPath *)indexPath {
    
    if (indexPath.column==0) {
//        if (indexPath.leftOrRight==0) {
//            NSDictionary *menuDic = [_data1 objectAtIndex:indexPath.row];
////            return [menuDic objectForKey:@"title"];
//            return _data1[indexPath.row];
//        } else{
//            NSInteger leftRow = indexPath.leftRow;
//            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
////            return [[menuDic objectForKey:@"data"] objectAtIndex:indexPath.row];
//            return _data1[indexPath.row];
//        }
        return @"";
    } else if (indexPath.column==1) {
        
        return _data2[indexPath.row];
        
    } else {
        
        return _data3[indexPath.row];
    }
}




@end
